這一次編輯器撰寫大概分類為:
一、新增矩形
二、刪除矩形
三、儲存現有狀態
四、匯入已儲存狀態
<div id="menu">
<button id="addRectangle">Add Rectangle</button>
<button id="deleteRectangle">Delete Rectangle</button>
<button id="saveState">Save State</button>
<button id="loadState">Load State</button>
</div>
<div id="container"></div>
<div id="info"></div>
新增矩形時,將依據colors陣列內,隨機選用一個顏色當作矩形的背景色。
const menu = document.getElementById('menu');
const container = document.getElementById('container');
const addRectangleButton = document.getElementById('addRectangle');
const deleteRectangleButton = document.getElementById('deleteRectangle');
const saveStateButton = document.getElementById('saveState');
const loadStateButton = document.getElementById('loadState');
const info = document.getElementById('info');
// color array
const colors = [
'rgba(0, 0, 255, 0.5)', // Blue
'rgba(0, 255, 0, 0.5)', // Green
'rgba(255, 0, 0, 0.5)', // Red
'rgba(255, 255, 0, 0.5)', // Yellow
'rgba(255, 0, 255, 0.5)', // Magenta
'rgba(0, 255, 255, 0.5)' // Cyan
];
function getRandomColor() {
return colors[Math.floor(Math.random() * colors.length)];
}
// addRectangleButton
addRectangleButton.addEventListener('click', function () {
const rectangle = document.createElement('div');
rectangle.classList.add('rectangle');
rectangle.style.width = '100px';
rectangle.style.height = '100px';
rectangle.style.backgroundColor = getRandomColor();
container.appendChild(rectangle);
})